package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.Result;
import entity.StatusCode;
import org.apache.catalina.manager.StatusManagerServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/spit")
@CrossOrigin
public class SpitController {

    @Autowired
    private SpitService spitService;

    @Autowired
    private RedisTemplate redisTemplate;

    //查询所有
    @RequestMapping(method = RequestMethod.GET)
    public Result list() {
        List<Spit> list = spitService.findAll();
        return new Result(StatusCode.OK, true, "查询成功", list);
    }

    //新增
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody Spit spit) {
        spitService.save(spit);
        return new Result(StatusCode.OK, true, "添加成功");
    }

    //根据id查询
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        Spit spit = spitService.findById(id);
        return new Result(StatusCode.OK, true, "查询成功", spit);
    }

    //根据id修改
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result findById(@RequestBody Spit spit, @PathVariable String id) {
        spit.set_id(id);
        spitService.update(spit);
        return new Result(StatusCode.OK, true, "修改成功");
    }


    //根据id删除
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        spitService.delete(id);
        return new Result(StatusCode.OK, true, "删除成功");
    }

    //根据上级ID查询吐槽列表（分页）
    @RequestMapping(value = "/comment/{parentid}/{page}/{size}", method = RequestMethod.GET)
    public Result comment(@PathVariable String parentid, @PathVariable int page, @PathVariable int size) {
        Page<Spit> page1 = spitService.findByParentid(parentid, page, size);
        return new Result(StatusCode.OK, true, "查询成功", page1.getContent());
    }


    @RequestMapping(value = "/thumbup/{spitId}", method = RequestMethod.PUT)
    public Result thumbup(@PathVariable String spitId){

        String userid = "123";
        //判断redis中是否存在些用户id    key:value
        String thumbup = (String) redisTemplate.opsForValue().get(spitId+"_"+userid);
        if(thumbup!=null){
            return new Result(StatusCode.REPERROR, false, "你已经点过赞了");
        }

        spitService.updateThumbup(spitId);
        redisTemplate.opsForValue().set(spitId+"_"+userid,"1");
        return new Result(StatusCode.OK, true, "点赞成功");
    }

    //todo 增加浏览量与分享数
}
